import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/record/category_list_entity.dart';
import 'package:sports_new/utils/utils.dart';
import '../../entity/record/player_entity.dart';
import '../../server/api/record_api.dart';
import 'channel_logic.dart';

class PlayerLogic extends GetxController {
  final String? seasonTag;
  PlayerLogic(this.leagueId, this.seasonTag);

  List<CategoryListEntity>? struct;
  List<String>? header;
  List<PlayerEntity>? playerAll;
  List<PlayerEntity>? playerHome;
  List<PlayerEntity>? playerGuest;
  int structIndex = 0;
  int leagueId;
  bool visible = false;
  EasyRefreshController refreshController = EasyRefreshController();
  late ChannelLogic channel;

  @override
  void onInit() {
    super.onInit();
    channel = Get.find<ChannelLogic>(tag: seasonTag);
    var currentSeason = channel.season;
    channel.addListener(() {
      if (currentSeason != channel.season) {
        getLeftData();
        currentSeason = channel.season;
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
    getLeftData();
  }

  void getLeftData() async {
    List<CategoryListEntity>? data =
      await RecordApi.getCategory(
        season: channel.season,
        seasonId: channel.seasonId,
        recordType: channel.recordType,
        leagueId: leagueId
      );
    if (data != null) {
      struct = data;
      update();
      if (struct!.isNotEmpty) {
        try {
          getData();
        } catch (e) {}
      }
    }
  }

  void getData() async {
    final result = await RecordApi.getPlayerData(
        season: channel.season,
        seasonId: channel.seasonId,
        leagueId: leagueId,
        searchType: struct![structIndex].key!,
        recordType: channel.recordType);
    header = result?.header ?? [];
    playerAll = result?.data?.all;
    playerHome = result?.data?.home;
    playerGuest = result?.data?.guest;
    update();
  }

  onSelectLeft(int index) {
    structIndex = index;
    update();
    getData();
  }

  void doRefresh() {
    if(refreshController.headerState?.mode.isIdle == false) return;
    refreshController.callRefresh();
  }
}
